package com.cby.android.base.net

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.cby.android.base.R
import java.io.File
import java.util.*

/**
 * @description: NetDownloadActivity
 * @author: ChenBaoYang
 * @createDate: 2022/8/22 1:51 下午
 */
class NetDownloadActivity : AppCompatActivity() {

    private lateinit var showTv: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_net_download)
        showTv = findViewById(R.id.tv_show)
    }

    fun onClickDownload(view: View) {
        //val url = "http://81.71.133.167:8080/RemoteDemo/api/file/v5nsjm.jpg"
        val url = "https://img2.doubanio.com/view/subject/l/public/s27264181.jpg"
        val r = "CXZ258654" + Random().nextInt(1000)
        val targetPath = getTargetFileDir()!!.absolutePath +File.separator+ r+".jpg"
        val helper = DownHelper(url, targetPath, 2)
        helper.start()
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                val completeRate = helper.completeRate
                val mDownStatus =  completeRate * 100
                runOnUiThread {
                    showTv.text = "已下载：${Math.floor(mDownStatus)}%"
                }

                //下载完全后取消任务调度
                if (mDownStatus >= 100) {
                    timer.cancel()
                }
            }

        },50, 100)

    }

    private fun getTargetFileDir(): File? {
        val file = getExternalFilesDir("files") ?: return null
        if (!file.exists()) {
            file.mkdirs()
        }
        return file
    }
}